<?php
/*
	微信会员卡激活
*/
defined('BY_JYA') or exit('error');
$_RQ['op']=$_RQ['op']?$_RQ['op']:'main';
cfc('core')->checklogin();
if($_SESSION['container']!='wechat' && $_SESSION['container']!='wxapp'){
	exi('不在微信环境，或者没有获取到用户openid，无法使用微信会员卡功能！','error');
}
$return=array();
$setting=uni_setting('wx_card_setting');
if($_RQ['op']=='main'){
		//领取微信会员卡，整理鉴权信息，交由前端发起会员卡领取操作
		$wxcard=uni_setting('wx_card_edit');
		if(!$wxcard || !$wxcard['card_id']){
			exi('会员卡不存在或已失效，无法领取！','error','goback');
		}
		$wechat=pdo_get('core_account_wechat',array('id'=>$_SESSION['wechat_id']),array('api_ticket','api_ticket_expire'));
		if(!$wechat['api_ticket'] || !$wechat['api_ticket_expire'] || $wechat['api_ticket_expire']<TIMESTAMP){
			$ticket_url='https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={access_token}&type=wx_card';
			$res=cfc('account')->request($ticket_url);
			$update=array(
				'api_ticket'=>$res['ticket'],
				'api_ticket_expire'=>TIMESTAMP+$res['expires_in']-100,
			);
			pdo_update('core_account_wechat',$update,array('id'=>$_SESSION['wechat_id']));
			$api_ticket=$res['ticket'];
		}else{
			$api_ticket=$wechat['api_ticket'];
		}
		$nonce_str=random(10);
		$arr = array($api_ticket,TIMESTAMP,$nonce_str,$wxcard['card_id']);
		sort($arr, SORT_STRING);
		$signature = sha1(implode($arr));
		$card_ext=array(
			'timestamp'=>TIMESTAMP,
			'nonce_str'=>$nonce_str,
			'signature'=>$signature,
		);
		$card_ext['timestamp']="{$card_ext['timestamp']}";
		$return['cardList']=array(
			array(
				'cardId'=>$wxcard['card_id'],
				'openid'=>$_SESSION['openid'],
				'cardExt'=>ijson_encode($card_ext),
			)
		);
		if($_RQ['getcode']){
			//获取URL
			$api_geturl='https://api.weixin.qq.com/card/membercard/activate/geturl?access_token={access_token}';
			$forms=array(
				'card_id'=>$wxcard['card_id'],
				'outer_str'=>$_SESSION['openid'],
			);
			$forms=ijson_encode($forms);	
			$return=cfc('account')->request($api_geturl,$forms);
			if($return['errcode']!=0){
				exi('领取会员卡失败！'.$return['errcode'].','.$return['errmsg'],'error');
			}
			//解析URL
			$arr = parse_url($return['url']);
			var_dump($arr);
			$queryParts = explode('&', $arr['query']); 	 
			$params = array(); 
			foreach ($queryParts as $param) { 
					$item = explode('=', $param); 
					$params[$item[0]] = $item[1]; 
			} 
			$return['extraData']=array(
				'encrypt_card_id'=>$params['encrypt_card_id'],
				'outer_str'=>$params['outer_str'],
				'biz'=>$params['biz'],
			);
			exi($return);
		}
		exi($return);
}
if($_RQ['op']=='active'){
	//激活微信会员卡
	$wxcard_code=pdo_getcolumn('core_fans',array('wxgid'=>$_SESSION['wechat_id'],'openid'=>$_SESSION['openid']),'wxcard_code');
	if(!$wxcard_code){
		exi('您尚未领取会员卡，请先领取（如果已经领取了，但还提示未领取：请联系管理员，查看微信公众号token验证情况！）！','error');
	}
	//引导用户填写激活信息	
	if($setting['active']){
		$htmls=array(
			'title'=>'填写激活信息',
			'list'=>array(),
		);
		if($setting['realname']){
			$htmls['list'][]=array('type'=>'string','name'=>'realname','title'=>'真实姓名');
		}
		if($setting['mobile']){
			$htmls['list'][]=array('type'=>'string','name'=>'mobile','title'=>'手机号');
		}
		if($setting['mobile_code'] && $setting['mobile_code_temp']){
			$htmls['list'][]=array('type'=>'mobile_code','name'=>'mobile_code','title'=>'验证码','mobile_field'=>'mobile','send_op'=>'send_code');
		}
		if(!empty($htmls['list'])){
			$return['item']=array(
				'code'=>$wxcard_code,
			);
			$htmls['list'][]=array('type'=>'submit','post'=>true,'url'=>'active_post','data'=>'item','title'=>'提交');
			$return['htmls']=$htmls;
			exi($return);
		}		
	}
	//无需填写激活信息，直接进入下一步
	$setting['active']=false;
	$_RQ['op']='active_post';
}
if($_RQ['op']=='active_post'){
	if($setting['active']){
		//保存激活信息
		$post=get_postdata();
		$update=array();
		if($setting['realname']){
			if(!$post['realname']){
				exi('请输入真实姓名！','error');
			}
			$update['realname']=trim($post['realname']);
		}
		if($setting['mobile']){
			if(!$post['mobile']){
				exi('请输入手机号！','error');
			}
			$update['mobile']=trim($post['mobile']);
		}
		if($setting['mobile_code']){
			if(!$post['mobile_code'] || $_SESSION['mobile_code']!=$post['mobile_code']){
				exi('验证码输入错误！','error');
			}
		}
		pdo_update('core_members',$update,array('id'=>$_SESSION['uid']));
		$wxcard_code=$post['code'];
	}
	//调用接口完成激活
	$wx_card_edit=uni_setting('wx_card_edit');
	if(!$wx_card_edit['card_id']){
		exi('指定会员卡不存在或已失效，无法激活！','error');
	}
	$params=array(
		'membership_number'=>$wxcard_code,
		'code'=>$wxcard_code,
		'card_id'=>$wx_card_edit['card_id'],
		'init_bonus'=>$setting['give_credit1']?intval($setting['give_credit1']):0,
		'init_balance'=>$setting['give_credit2']?intval($setting['give_credit2']):0,
	);
	$params=ijson_encode($params);
	$api_url='https://api.weixin.qq.com/card/membercard/activate?access_token={access_token}';
	cfc('account')->request($api_url,$params);
	exi('激活微信会员卡成功！','','closeWindow');
}
if($_RQ['op']=='send_code'){
	$post=get_postdata();
	$mobile=intval($post['mobile']);
	if(!$mobile){
		exi('手机号格式错误！','error');
	}
	$check=pdo_getcolumn('core_members',array('uniacid'=>$_SESSION['uniacid'],'mobile'=>$mobile),'id');
	if($check && $check!=$_SESSION['uid']){
		exi('手机号码已被占用，请更换！','error');
	}
	$code=rand(100000,999999);
	$_SESSION['smscode']=$code;
	$content=array('code'=>$_SESSION['smscode']);
	$result=cfc('core')->sendsms($mobile,$content,$setting['mobile_code_temp']);
	if(is_error($result)){
		exi('验证码发送失败：'.$result['message'],'error');
	}
	if(!$result){
		exi('error');
	}else{
		exi('success');
	}
}